package com.taxsearch.commons;

/**
 * @description: token拦截器
 *
 * @author: 杜一平
 *
 * @create: 2018年8月10日-上午11:09:38
 **/
import com.taxsearch.dao.TokenMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;

import java.io.PrintWriter;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Controller
@Component
public class TokenInterceptor implements HandlerInterceptor {

	@Autowired
	private TokenMapper tokenMapper;

	/**
	 * 请求之前
	 * 
	 * @param request 请求对象
	 * @param response 返回对象
	 * @param o
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object o) throws Exception {

		System.out.println("当前请求来："+request.getRequestURI());
		// 自动排除生成token的路径,并且如果是options请求是cors跨域预请求，设置allow对应头信息
		if (request.getRequestURI().equals("/getToken")
				|| RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
			return true;
		}
		// 获取请求头中token
//		final String authHeader = request.getHeader("HangXinAuthToken");
		// 获取请求信息中的token
//		byte[] requestBody = StreamUtils.copyToByteArray(request.getInputStream());
//        JSONObject jsonObject = JSON.parseObject((new String(requestBody, "UTF-8")));
//        final String authHeader=jsonObject.getString("HangXinAuthToken");
         String authHeader=request.getParameter("token").toString();
        
		try {
			// 如果没有header信息
			if (authHeader == null || authHeader.trim() == "") {
				throw new SignatureException("安全校验不通过！");
			}

			// 获取jwt实体对象接口实例
			final Claims claims = Jwts.parser()
					.setSigningKey("HangXinAuthv1.0.0")
					.parseClaimsJws(authHeader).getBody();
			// 获取id
			String id = claims.getSubject();
			
//			// 校验数据库信息，由于密码暂缺，暂不考虑
//			judgeToken(id,authHeader);
		}
		// 验证异常处理
		catch (SignatureException | ExpiredJwtException e) {
			// 输出对象
			PrintWriter writer = response.getWriter();

			// 输出error消息
			writer.write("token error!");
			writer.close();
			return false;
		}
		// 出现异常时
		catch ( Exception e) {
			// 输出对象
			PrintWriter writer = response.getWriter();
			// 输出error消息
			writer.write(e.getMessage());
			writer.close();
			return false;
		}
		return true;
	}
	/**
	 * 
	 * @Title: judgeToken
	 * @Description: 需要验证数据库的token
	 * @param: @param id
	 * @param: @param authHeader  
	 * @return: void   
	 * @throws
	 */
	public void judgeToken(String id,String authHeader) throws SignatureException{
		// 从数据库中获取token
		List<HashMap<String, String>> tokenList = tokenMapper
				.selectToken(id);
		// 数据库中的token值
		String tokenval = null;
		if (tokenList.size() != 0) {
			tokenval = String.valueOf(tokenList.get(0).get("TOKEN"));
		}

		// 如果内存中不存在,提示客户端获取token
		if (tokenval == null || tokenval.trim() == "") {
			throw new SignatureException(
					"token错误！");
		}
		// 判断内存中的token是否与客户端传来的一致
		if (!tokenval.equals(authHeader)) {
			throw new SignatureException(
					"token错误！");
		}
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, Object o, Exception e)
			throws Exception {

	}

}